package com.xxh.blog.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxh.blog.config.RabbitMqConfig;
import com.xxh.blog.dao.CategoryDao;
import com.xxh.blog.dao.CommentDao;
import com.xxh.blog.dao.EssayDao;
import com.xxh.blog.entity.Category;
import com.xxh.blog.entity.Comment;
import com.xxh.blog.entity.Essay;
import com.xxh.blog.entity.UserMessage;
import com.xxh.blog.entity.vo.CommentVo;
import com.xxh.blog.entity.vo.EssayDetailVo;
import com.xxh.blog.entity.vo.EssayVo;
import com.xxh.blog.mq.PostMqMessage;
import com.xxh.blog.service.CommentService;
import com.xxh.blog.service.UserMessageService;
import com.xxh.blog.shiro.AccountProfile;
import com.xxh.blog.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
public class essayController {

    @Resource
    com.xxh.blog.service.essayService essayService;

    @Autowired
    EssayDao essayDao;

    @Resource
    CommentService commentService;


    @Autowired
    CommentDao commentDao;
    @Resource
    UserMessageService userMessageService;

    @Resource
    CategoryDao categoryDao;

    @Autowired
    AmqpTemplate amqpTemplate;

    /**
     * 根据分类ID查询文章列表
     *
     * @param id    分类ID
     * @param model
     * @return
     */
    @RequestMapping("/essay/category/{id}")
    public String category(@PathVariable long id, Model model, HttpServletRequest request) {

        model.addAttribute("curCategoryID", id);
        Integer curpage = request.getParameter("curpage") == null ? 1 : Integer.parseInt(request.getParameter("curpage"));
        Integer size = request.getParameter("size") == null ? 5 : Integer.parseInt(request.getParameter("size"));
        Page page = new Page(curpage, size);
        IPage<EssayVo> paging = essayService.paging(page, Math.toIntExact(id), null, null, null, null);
        model.addAttribute("categoryEssayListData", paging);
        return "/essay/category";
    }


    /**
     * 获取文章详情与评论
     *
     * @param id 文章ID
     * @return
     */
    @RequestMapping("/essay/detail/{id}")
    public String detail(@PathVariable Long id, Model model, HttpServletRequest request) {

        //获取文章详情
        EssayDetailVo vo = essayService.selectDetail(new Page(), Math.toIntExact(id));

        //文章的阅读数+1
        essayService.putViewCount(vo);
        model.addAttribute("essayDetail", vo);


        Integer curpage = request.getParameter("curpage") == null ? 1 : Integer.parseInt(request.getParameter("curpage"));
        Integer size = request.getParameter("size") == null ? 2 : Integer.parseInt(request.getParameter("size"));

        //获取文章下的评论
        IPage<CommentVo> commentVoIPage = commentService.paging(new Page(curpage, size), Math.toIntExact(vo.getId()), null, null);
        model.addAttribute("commentData", commentVoIPage);
        return "/essay/detail";
    }


    /**
     * 编辑文章
     * @return 返回编辑文章的视图
     */
    @RequestMapping("/essay/edit")
    public String edit(long id,HttpServletRequest request,Model model){


        Essay essay = essayService.getById(id);
        AccountProfile profile = (AccountProfile) SecurityUtils.getSubject().getPrincipal();
        //文章作者不是当前用户，出现非法请求
        Assert.isTrue(essay.getUserId().equals(profile.getId()), "没有权限操作文章");

        model.addAttribute("essay", essay);
        List<Category> categories = categoryDao.selectList(null);
        model.addAttribute("categories", categories);
        return "/essay/edit";
    }

    /**
     * 添加文章
     * @param model
     * @return 返回添加文章的视图
     */
    @RequestMapping("/essay/add")
    public String add(Model model){


        List<Category> categories = categoryDao.selectList(null);
        model.addAttribute("categories",categories);
        return "/essay/add";
    }

    /**
     * 修改文章
     * @param essay 文章实体
     * @return
     */
    @PostMapping("/essay/save")
    @ResponseBody
    public Result Save(Essay essay,long id){

        Essay essay1 = essayService.getById(id);

        essay1.setTitle(essay.getTitle());
        essay1.setContent(essay.getContent());
        essay1.setCategoryId(essay.getCategoryId());
        //更新到数据库
        essayService.updateById(essay1);
        //MQ通知ES更新数据
        amqpTemplate.convertAndSend(RabbitMqConfig.ES_EXCHANGE,RabbitMqConfig.ES_Key,new PostMqMessage(essay1.getId(),PostMqMessage.CREATE_OR_UPDATE));
        return Result.ok("完成").put("action","/essay/detail/"+id);
    }

    @PostMapping("/essay/insert")
    @ResponseBody
    public Result InsertEssay(Essay essay){
        AccountProfile profile = (AccountProfile) SecurityUtils.getSubject().getPrincipal();
        Long uid = profile.getId();

        Essay tempessay = new Essay();
        tempessay.setCategoryId(essay.getCategoryId());
        tempessay.setContent(essay.getContent());
        tempessay.setTitle(essay.getTitle());
        tempessay.setUserId(uid);
        tempessay.setVoteUp(0);
        tempessay.setVoteDown(0);
        tempessay.setCommentCount(0);
        tempessay.setRecommend(false);
        tempessay.setLevel(false);
        tempessay.setStatus((byte)1);
        tempessay.setCreated(new Date());
        tempessay.setModified(new Date());
        tempessay.setViewCount(0);
        tempessay.setEditMode("0");
        //保存到数据库
        essayService.save(tempessay);
        //获取插入后的ID
        Long id = tempessay.getId();
        //MQ通知ES更新数据
        amqpTemplate.convertAndSend(RabbitMqConfig.ES_EXCHANGE,RabbitMqConfig.ES_Key,new PostMqMessage(id,PostMqMessage.CREATE_OR_UPDATE));
        return Result.ok("完成").put("action","/essay/detail/"+id);
    }

    @PostMapping("/essay/delete")
    @ResponseBody
    public Result deleteEssay(long id){

        //通知MQ删除数据
        amqpTemplate.convertAndSend(RabbitMqConfig.ES_EXCHANGE,RabbitMqConfig.ES_Key,new PostMqMessage(id,PostMqMessage.REMOVE));
        Result result =essayService.removeById(id)?Result.ok("删除成功"):Result.error("出错了");

        return result;
    }

    /**
     * 设置文章加精，置顶
     * @param id 文章ID
     * @param rank 0:取消加精（置顶） 1:确认加精（置顶）
     * @param field 操作类型：stick：置顶，status:加精
     * @return
     */
    @PostMapping("/essay/set")
    @ResponseBody
    public Result essaySet(int id,int rank,String field){
        Essay essayTemp = essayService.getById(id);
        if(field.equals("stick")){
            essayTemp.setLevel(rank==1);
        }else if(field.equals("status")){
            essayTemp.setRecommend(rank==1);
        }
        if(essayService.updateById(essayTemp)){

            //通知MQ更新数据
            amqpTemplate.convertAndSend(RabbitMqConfig.ES_EXCHANGE,RabbitMqConfig.ES_Key,new PostMqMessage(essayTemp.getId(),PostMqMessage.CREATE_OR_UPDATE));
            return Result.ok();
        }else {
            return Result.error("出错了");
        }

    }

    /**
     * 评论文章
     * @param eid 文章ID
     * @param content 回复内容
     * @return
     */
    @PostMapping("/essay/reply")
    @ResponseBody
    public Result replay(long eid,String content){


        //获取当前用户ID
        AccountProfile profile = (AccountProfile) SecurityUtils.getSubject().getPrincipal();
        Long currentUserId = profile.getId();

        //获取发布文章的用户ID
        Essay essay = essayService.getById(eid);
        Long essayUserId = essay.getUserId();

        //评论表新增一条评论
        Comment comment = new Comment();

        comment.setParentId((long) 0);
        comment.setPostId(eid);
        comment.setUserId(currentUserId);
        comment.setContent(content);

        commentDao.insert(comment);
        //文章表评论数+1
        essay.setCommentCount(essay.getCommentCount()+1);
        essayService.updateById(essay);

        //用户消息表新增一条记录
        UserMessage message = new UserMessage();
        message.setFromUserId(currentUserId);
        message.setToUserId(essayUserId);
        message.setCreated(new Date());
        message.setModified(new Date());
        message.setContent(content);
        message.setStatus(0);
        userMessageService.save(message);

        return Result.ok();
    }


}
